"""展示角色属性系统"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from models.character import Character, CharacterType
from game.game_manager import GameManager

def print_separator(title=""):
    """打印分隔线"""
    if title:
        print(f"\n{'='*20} {title} {'='*20}")
    else:
        print("="*60)

def show_character_details(character):
    """显示角色详细信息"""
    print(f"\n📋 角色: {character.name} ({character.character_type.value})")
    print(f"🆔 ID: {character.id}")
    
    print("\n🔹 基础属性:")
    print(f"  ❤️  生命值: {character.current_hp}/{character.max_hp}")
    print(f"  ⚔️  攻击力: {character.attack}")
    print(f"  🛡️  防御力: {character.defense}")
    print(f"  💨 速度: {character.speed}")
    
    print("\n🔸 战斗属性:")
    print(f"  🎯 命中率: {character.hit_rate}%")
    print(f"  💫 闪避率: {character.dodge_rate}%")
    print(f"  💥 暴击率: {character.crit_rate}%")
    print(f"  🔥 暴击伤害: {character.crit_damage}%")
    
    print(f"\n📍 位置: ({character.position_x}, {character.position_y})")
    print(f"💚 状态: {'存活' if character.is_alive else '死亡'}")

def show_attribute_comparison():
    """显示属性对比"""
    print_separator("角色属性对比")
    
    # 创建不同类型的角色进行对比
    characters = [
        Character(
            id="tank", name="重装战士", character_type=CharacterType.PLAYER,
            max_hp=200, current_hp=200, attack=20, defense=25, speed=8,
            hit_rate=80, dodge_rate=5, crit_rate=10, crit_damage=130
        ),
        Character(
            id="dps", name="狂战士", character_type=CharacterType.PLAYER,
            max_hp=120, current_hp=120, attack=40, defense=10, speed=15,
            hit_rate=90, dodge_rate=10, crit_rate=25, crit_damage=180
        ),
        Character(
            id="assassin", name="刺客", character_type=CharacterType.PLAYER,
            max_hp=80, current_hp=80, attack=35, defense=8, speed=25,
            hit_rate=95, dodge_rate=30, crit_rate=35, crit_damage=220
        ),
        Character(
            id="mage", name="元素法师", character_type=CharacterType.PLAYER,
            max_hp=70, current_hp=70, attack=45, defense=5, speed=20,
            hit_rate=95, dodge_rate=15, crit_rate=30, crit_damage=200
        ),
        Character(
            id="healer", name="圣职者", character_type=CharacterType.PLAYER,
            max_hp=100, current_hp=100, attack=15, defense=15, speed=18,
            hit_rate=85, dodge_rate=20, crit_rate=5, crit_damage=120
        )
    ]
    
    # 表格头部
    print(f"{'角色':<12} {'生命':<8} {'攻击':<6} {'防御':<6} {'速度':<6} {'命中':<6} {'闪避':<6} {'暴击':<6} {'暴伤':<6}")
    print("-" * 80)
    
    # 显示每个角色的属性
    for char in characters:
        print(f"{char.name:<12} {char.max_hp:<8} {char.attack:<6} {char.defense:<6} {char.speed:<6} "
              f"{char.hit_rate}%{'':<3} {char.dodge_rate}%{'':<3} {char.crit_rate}%{'':<3} {char.crit_damage}%")
    
    print("\n🔍 角色特点分析:")
    print("• 重装战士: 高生命高防御，适合承受伤害")
    print("• 狂战士: 高攻击高暴击，输出稳定")
    print("• 刺客: 高速度高闪避高暴击，爆发输出")
    print("• 元素法师: 超高攻击和暴击伤害，脆皮法师")
    print("• 圣职者: 平衡属性，专注治疗支援")

def show_combat_simulation():
    """显示战斗模拟"""
    print_separator("战斗模拟演示")
    
    # 创建攻击者和防御者
    attacker = Character(
        id="attacker", name="攻击者", character_type=CharacterType.PLAYER,
        max_hp=100, current_hp=100, attack=30, defense=10, speed=15,
        hit_rate=85, dodge_rate=10, crit_rate=20, crit_damage=150
    )
    
    defender = Character(
        id="defender", name="防御者", character_type=CharacterType.ENEMY,
        max_hp=100, current_hp=100, attack=25, defense=15, speed=12,
        hit_rate=80, dodge_rate=25, crit_rate=15, crit_damage=140
    )
    
    print("🥊 战斗双方:")
    print(f"攻击方: {attacker.name} (攻击={attacker.attack}, 命中={attacker.hit_rate}%, 暴击={attacker.crit_rate}%)")
    print(f"防御方: {defender.name} (防御={defender.defense}, 闪避={defender.dodge_rate}%)")
    
    print("\n⚔️ 模拟5次攻击:")
    
    total_damage = 0
    hit_count = 0
    crit_count = 0
    dodge_count = 0
    
    for i in range(5):
        # 计算命中和暴击
        is_hit = attacker.calculate_hit_chance(defender.dodge_rate)
        is_crit = False
        if is_hit:
            is_crit = attacker.calculate_crit_chance()
        
        # 计算伤害
        base_damage = max(1, attacker.attack - defender.defense)
        
        # 应用伤害
        damage_result = defender.take_damage(base_damage, is_crit=is_crit, is_hit=is_hit)
        
        # 统计
        if damage_result['is_hit']:
            hit_count += 1
            total_damage += damage_result['actual_damage']
            if damage_result['is_crit']:
                crit_count += 1
        else:
            dodge_count += 1
        
        # 显示结果
        status_icons = []
        if not damage_result['is_hit']:
            status_icons.append("💫闪避")
        elif damage_result['is_crit']:
            status_icons.append("💥暴击")
        else:
            status_icons.append("🎯命中")
        
        print(f"第{i+1}次: {damage_result['actual_damage']}伤害 {' '.join(status_icons)}")
        
        # 恢复生命值继续测试
        defender.current_hp = defender.max_hp
    
    print(f"\n📊 统计结果:")
    print(f"命中: {hit_count}/5 ({hit_count*20}%)")
    print(f"暴击: {crit_count}/5 ({crit_count*20}%)")
    print(f"闪避: {dodge_count}/5 ({dodge_count*20}%)")
    print(f"总伤害: {total_damage}")
    print(f"平均伤害: {total_damage/5:.1f}")

def show_sample_characters():
    """显示示例角色"""
    print_separator("示例角色展示")
    
    game_manager = GameManager()
    player_chars, enemy_chars = game_manager.create_sample_characters()
    
    print("👥 玩家方角色:")
    for char in player_chars:
        show_character_details(char)
    
    print("\n👹 敌方角色:")
    for char in enemy_chars:
        show_character_details(char)

def show_attribute_effects():
    """显示属性效果说明"""
    print_separator("属性效果说明")
    
    print("🎯 命中率 (Hit Rate):")
    print("  • 决定攻击是否能够命中目标")
    print("  • 与目标的闪避率进行对抗")
    print("  • 公式: 实际命中率 = 攻击者命中率 - 目标闪避率")
    print("  • 范围: 通常在70%-95%之间")
    
    print("\n💫 闪避率 (Dodge Rate):")
    print("  • 决定是否能够完全闪避攻击")
    print("  • 闪避成功时伤害为0")
    print("  • 高敏捷角色通常有更高的闪避率")
    print("  • 范围: 通常在5%-30%之间")
    
    print("\n💥 暴击率 (Critical Rate):")
    print("  • 决定是否触发暴击伤害")
    print("  • 只有在攻击命中时才能触发")
    print("  • 暴击时伤害按暴击伤害倍数计算")
    print("  • 范围: 通常在10%-35%之间")
    
    print("\n🔥 暴击伤害 (Critical Damage):")
    print("  • 暴击时的伤害倍数")
    print("  • 以百分比表示，150%表示1.5倍伤害")
    print("  • 高攻击角色通常有更高的暴击伤害")
    print("  • 范围: 通常在130%-220%之间")
    
    print("\n⚡ 速度 (Speed):")
    print("  • 决定战斗中的行动顺序")
    print("  • 速度越高越早行动")
    print("  • 影响战斗的主动权")
    print("  • 范围: 通常在8-25之间")

def main():
    """主函数"""
    print("🎮 角色属性系统展示")
    print("=" * 60)
    
    try:
        show_sample_characters()
        show_attribute_comparison()
        show_combat_simulation()
        show_attribute_effects()
        
        print_separator("展示完成")
        print("✅ 角色属性系统功能完整!")
        print("\n🚀 快速开始:")
        print("• 运行 python demo.py 体验完整游戏")
        print("• 运行 python test_combat_attributes.py 测试战斗系统")
        print("• 运行 python visualize_battlefield.py 查看战场布局")
        
    except Exception as e:
        print(f"❌ 展示失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()